-module(register).
-export([register/1]).
-import(db_user, [insert_user/7, get_user/1]).


% Manage the register action
register(A) ->
	% Parse the request and obtain the values entered by the user
	L = yaws_api:parse_post(A),
	Name = utils:value_from_key("username", L),
	Pwd = utils:value_from_key("password", L),
	Email = utils:value_from_key("email", L),
	Language = list_to_atom(utils:value_from_key("language", L)),
	case Name =:= error of
	
		% If the user didn't enter values
		true ->
			{redirect, index};
			
		% If the user entered values
		false ->
			case get_user(list_to_atom(Name)) of
			
				% If there is no user in the database with the name Name, the new user is inserted
				{atomic, []} ->
					if
						Language =:= learn_spanish ->
							insert_user(list_to_atom(Name), list_to_atom(Pwd), list_to_atom(Email), 0, 1, 1, 0);
						true ->
							insert_user(list_to_atom(Name), list_to_atom(Pwd), list_to_atom(Email), 1, 0, 0, 1)
					end,	
					{redirect, index};
					
				% If exists a user with the name Name, an error is reported
				{atomic, _} ->
					{alreadyexists}
			end
	end.
